package com.lambda.hybrid;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;

public class ToolbarItem extends View {
    private Paint mPaint = new Paint();

    private String mText;
    private Drawable mDrawable;

    public ToolbarItem(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ToolbarItem(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        TypedArray arr = context.obtainStyledAttributes(attrs, R.styleable.ToolbarItem);
        mText = arr.getString(R.styleable.ToolbarItem_tbiText);
        mPaint.setColor(arr.getColor(R.styleable.ToolbarItem_tbiColor, Color.BLACK));
        mPaint.setTextSize(arr.getDimensionPixelSize(R.styleable.ToolbarItem_tbiTextSize, 38));
        mDrawable = arr.getDrawable(R.styleable.ToolbarItem_tbiImage);
        arr.recycle();

        mPaint.setAntiAlias(true);
        mPaint.setTypeface(Typeface.DEFAULT_BOLD);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        ViewGroup parent = (ViewGroup) getParent();
        int spec = MeasureSpec.makeMeasureSpec(parent.getMeasuredHeight(), MeasureSpec.EXACTLY);
        super.onMeasure(spec, spec);
    }

    public void setText(String text) {
        mText = text;
        mDrawable = null;
        postInvalidate();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        if (mDrawable != null) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                mDrawable.setTint(mPaint.getColor());
            }
            int measure = getMeasuredHeight();
            mDrawable.setBounds(0, 0, measure, measure);
            mDrawable.draw(canvas);
        }

        if (!TextUtils.isEmpty(mText)) {
            Paint.FontMetrics metrics = mPaint.getFontMetrics();
            float textWidth = mPaint.measureText(mText);
            float textHeight = metrics.bottom - metrics.top;
            float measureWidth = getMeasuredWidth();
            float measureHeight = getMeasuredHeight();
            float minHeight = (measureHeight - textHeight) / 2;
            canvas.drawText(mText, (measureWidth - textWidth) / 2, minHeight + (metrics.leading - metrics.top), mPaint);
        }
    }

    public void setDrawable(Drawable drawable) {
        mDrawable = drawable;
        mText = null;
        postInvalidate();
    }
}
